package com.time.company.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.app.WXManager;
import com.time.company.base.BaseActivity;
import com.time.company.components.MainActivity;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.MyLoginInfo;
import com.time.company.utils.JpushUtils;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.LoginParameters;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

/*
* 这个是必须要在wxapi文件夹下建立的一个类
* 用来接收分享/登录结果
* */
public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {

    private static WXEntryActivity mInstance;
    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;
    private static String GET_REQUEST_ACCESS_TOKEN_URL =
            "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&" +
                    "secret=SECRET&code=CODE&grant_type=authorization_code";
    private static String GET_REQUEST_USER_INFO =
            "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInstance = WXEntryActivity.this;
        api = WXAPIFactory.createWXAPI(this, getString(R.string.wx_app_id), true);
        api.registerApp(getString(R.string.wx_app_id));
        //注意：
        //第三方开发者如果使用透明界面来实现WXEntryActivity，
        // 需要判断handleIntent的返回值，如果返回值为false，
        // 则说明入参不合法未被SDK处理，应finish当前透明界面，
        // 避免外部通过传递非法参数的Intent导致停留在透明界面，引起用户的疑惑
        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //如果分享的时候，该已经开启，那么微信开始这个activity时，会调用onNewIntent，所以这里要处理微信的返回结果
        setIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        setIntent(intent);
        api.handleIntent(intent, this);
    }


    //微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                break;
            default:
                break;
        }
        Logger.d("微信 " + req.getType());
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        int result;
        String code;
        switch (resp.errCode) {

            case BaseResp.ErrCode.ERR_OK:
                result = R.string.error_code_success;
                if (resp instanceof SendAuth.Resp) {
                    SendAuth.Resp aures = (SendAuth.Resp) resp;
                    code = aures.code;//响应成功，返回code
                    //微信授权返回结果，处理授权后操作,获取微信token
//                    if (NetWorkHelper.isNetAvailable(this)) {
//                        getAccessToken(code);
//                    }else {
//                        ToastUtils.showShort(R.string.network_abnormal_and_check);
//                    }
                    return;
                }else {
                    finish();
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = R.string.error_code_cancel;
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = R.string.error_code_deny;
                finish();
                break;
            default:
                result = R.string.error_code_unknown;
                finish();
                break;
        }
        Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
    }


    private void wechatLogin(String code) {
        if (NetWorkUtils.isNetAvailable(this)) {
            Request request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_wechatLoginForApp));

            String jpushId;
            if (TextUtils.isEmpty(JpushUtils.getRegisterId(application))) {
                jpushId = getString(R.string.zero);
            } else {
                jpushId = JpushUtils.getRegisterId(application);
            }
            parameters.setJpushId(jpushId);
            parameters.setCode(code);
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, 11,
                    true, false, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (null == basicBean) {
            return;
        }

        if (basicBean.isSuccess()) {
            // 授权成功，绑定微信的老用户
            MyLoginInfo myLoginInfo = basicBean.parseData(MyLoginInfo.class);
            application.setLogin(true);
            application.setTelephone(myLoginInfo.getTelephone());
            application.setAccount(myLoginInfo.getUserId());
            application.setToken(myLoginInfo.getToken());
            startActivity(new Intent(this, MainActivity.class));
            finish();

        } else if (TextUtils.equals(basicBean.getStatusCode(), "10308")) {
            // 授权失败
            ToastUtils.showShort(basicBean.getMsg());
            finish();

        } else if (TextUtils.equals(basicBean.getStatusCode(), "10309")) {
            MyLoginInfo myLoginInfo = basicBean.parseData(MyLoginInfo.class);
            if (null != myLoginInfo) {
                // 未绑定微信用户
//                WxAttachTeleActivity.start(this, myLoginInfo.getWeixinId());
                finish();
            }

        } else {
            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    //    private void getAccessToken(final String code) {
//        new Thread(new Runnable() {
//
//            @Override
//            public void run() {
//                try {
//                    String result = HttpUtils.getWxToken(getTokenRequest(code).toString());
//                    org.json.JSONObject jo = new org.json.JSONObject(result);
//                    String jsonResult = jo.getString("result");
//                    if (!TextUtils.isEmpty(result)) {
//
//                        JSONObject json = JSON.parseObject(jsonResult);
//                        LogTrace.i("json : " + json);
//                        if (json == null) {
//                            return;
//                        } else {
//                            WxAccessToken wToken = null;
//                            wToken = JSON.toJavaObject(json, WxAccessToken.class);
//                            CspeApplication.getInstance().setWxAccessToken(wToken);
//
//                            LogTrace.e("WxAccessToken : " + wToken.toString());
//
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
////                                    getUserInfo();
//                                }
//                            });
//                        }
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//            }
//        }).start();
//    }

//    /**
//     * 获取微信userInfo
//     */
////    private void getUserInfo(){
////        new Thread(new Runnable() {
////
////            @Override
////            public void run() {
////                try {
////                    final String result = HttpUtils.getWxToken(getUserInfoRequest().toString());
////                    org.json.JSONObject jo = new org.json.JSONObject(result);
////                    final String jsonResult = jo.getString("result");
////                    LogTrace.e("result : " + jsonResult);
//////					JSONObject json = JSON.parseObject(jsonResult);
////                    if (!TextUtils.isEmpty(jsonResult)) {
////                        //					JSONObject json = JSON.parseObject(result);
////                        //					if (json == null) {
////                        //						return;
////                        //					} else {
////                        runOnUiThread(new Runnable() {
////                            @Override
////                            public void run() {
////                                //获取我们的用户信息 openId 和 userInfo json
//////                                loginToServer(jsonResult);
////                            }
////                        });
////                        //					}
////
////                    }else {
////                        return;
////                    }
////
////                } catch (JSONException e) {
////                    e.printStackTrace();
////                }
////            }
////        }).start();
////    }
////    private void loginToServer(final String userInfo) {
////        Map<String, String> map = new HashMap<>();
////        map.put("command", "loginWechatThreePart");
////        map.put("platform", "android");
////        map.put("userInfo", userInfo);
////        map.put("openId", CspeApplication.getInstance().getWxAccessToken().getOpenId());
////        Request request = new Request(Constant.API, map, RequestMethod.POST);
////        request.setCallback(new StringCallback() {
////
////            @Override
////            public void onSuccess(String result) {
////
////                LogTrace.d("--------- onSuccess");
////                new EventTask().execute(Constant.LABEL);
////
////                //发送一个广播回到注册登录界面
////                Intent intent = new Intent(Constant.WECHAT);
////                sendBroadcast(intent);
////
////                mInstance.finish();
////            }
////
////            public String postRequest(String t) {
////                LogTrace.d("--------- postRequest t :" + t);
////                try {
////                    new ParseUserData().postData(t, Constant.WECHAT);
////                } catch (AppException e) {
////                    e.printStackTrace();
////                }
////                return super.postRequest(t);
////            }
////
////            @Override
////            public void onFailure(AppException e) {
////                LogTrace.d("--------- onFailure e : " + e);
////                ToastUtils.showShort(e.getMessage());
////                mInstance.finish();
////            }
////        }.setEncryptable(false));
////        // ;
////        requestManager.prefromRequest(request);
////    }

//    @Override
//    public void onSuccess(WxAccessToken result) {
//        //获取的微信token
//        CspeApplication.getInstance().setWxAccessToken(result);
//        LogTrace.e("token:--->>" + result);
//        LogTrace.e("token:errcode:--->>" + result.errcode);
//        LogTrace.e("token:errmsg:--->>" + result.errmsg);
//        LogTrace.e("token:expires_in-->>" + result.expires_in);
//        LogTrace.e("token:access_token:--->>" + result.access_token);
////        WXManager.instance().getWxUserInfo(this);
//        getUID(result.openId, result.access_token);//由token和openid获取用户信息
//        finish();
//    }

//    @Override
//    public void onFailed(int statusCode) {
//        Toast.makeText(WXEntryActivity.this, R.string.net_error_text, Toast.LENGTH_SHORT).show();
//        finish();
//    }

    //    private void getUID(final String openId, final String accessToken) {//获取用户微信信息
//        new Thread() {//开启异步线程请求接口获取用户信息
//            @Override
//            public void run() {
//                String path = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId;
//                org.json.JSONObject jsonObject = null;
//                try {
//                    jsonObject = JsonUtils.initSSLWithHttpClinet(path);
//                    String nickname = jsonObject.getString("nickname");
//                    String unionid = jsonObject.getString("unionid");
//                    String headimgurl = jsonObject.getString("headimgurl");
//                    LogTrace.e("nickname = " + nickname);
//                    LogTrace.e("unionid = " + unionid);
//                    LogTrace.e("headimgurl=" + headimgurl);
//                } catch (ClientProtocolException e) {
//                    e.printStackTrace();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
//    }

    private static String getTokenRequest(String code) {
        String tokenRequest = GET_REQUEST_ACCESS_TOKEN_URL.replace("APPID",
                mInstance.getString(R.string.wx_app_id)).
                replace("SECRET", mInstance.getString(R.string.wx_app_secret)).
                replace("CODE", code);
        Logger.i("---------- tokenRequest : " + tokenRequest);
        return tokenRequest;
    }

}
